package com.class06.mapper.impl;

import com.class06.mapper.StudentMapper;
import com.class06.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public class StudentMapperImpl implements StudentMapper{
    @Autowired    //相当于扫描后把对象放到jdbcTemplate对象中
//    private JdbcTemplate jdbcTemplate = new JdbcTemplate();
    private JdbcTemplate jdbcTemplate;

    @Override
    public void insertStudent(Student student) {
//        判断学生信息是否为空
        if (student==null || student.getId() == null){
            throw new RuntimeException("学生信息不能为空");
        }
        String sql = "insert into students values(?,?,?,?,?)";
//        执行sql语句
        int update = jdbcTemplate.update(sql, student.getId(),
                student.getName(), student.getGender(),
                student.getAge(), student.getClasses());
//        判断是否添加成功
        if (update > 0) {
            System.out.println("添加成功");
        }
    }

    @Override
    public List<Student> selectStudents() {
        //        1、创建sql语句  如果java实体类和数据库表名不一致，需要使用as关键字进行映射
        String sql = "select id,name,gender,age,class as classes from students";
        List<Student> studentList =  jdbcTemplate.query(sql,
                new BeanPropertyRowMapper<>(Student.class));
        return studentList;
    }
}
